import { PlusOutlined } from '@ant-design/icons'
import {
    Row,
    Typography,
    Flex,
    Button,
    Col,
    Form,
    Input,
    Modal,
    Table,
    Switch,
    Divider,
    Radio,
    Select,
    message
} from 'antd'
import React, { useState, useEffect } from 'react'
import { accountAddAPI, accountDelAPI, accountResetAPI, accountListAPI } from '../service/account'
import { sellerVerifyList } from '../service/seller'

function PrivilegeAccount() {
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [form] = Form.useForm()
    const [searchForm] = Form.useForm()
    const [accountList, setAccountList] = useState([])
    const [sellerList, setSellerList] = useState([])
    const [accountType, setAccountType] = useState(0)
    const [loading, setLoading] = useState(false)
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    })

    // 获取账号列表
    const fetchAccountList = async () => {
        setLoading(true)
        try {
            const params = {
                accountPhone: searchForm.getFieldValue('phone') || '',
                nickname: searchForm.getFieldValue('username') || '',
                pageNo: pagination.current,
                pageSize: pagination.pageSize
            };
            const res = await accountListAPI(params)
            if (res.code === '0') {
                setAccountList(res.data?.list || [])
                setPagination({
                    ...pagination,
                    total: res.data?.total || 0,
                })
            } else {
                message.error(res.message || '获取账号列表失败')
            }
        } catch (error) {
            message.error('获取账号列表失败')
        } finally {
            setLoading(false)
        }
    }

    // 获取商家列表
    const fetchSellerList = async () => {
        try {
            const res = await sellerVerifyList({ pageSize: 1000, pageNo: 1 })
            setSellerList(res.data.objects || [])
        } catch (error) {
            message.error('获取商家列表失败')
        }
    }

    useEffect(() => {
        fetchAccountList()
        fetchSellerList()
    }, [pagination.current, pagination.pageSize])

    const handleSearch = async () => {
        await fetchAccountList()
    }

    const handleReset = () => {
        searchForm.resetFields()
        fetchAccountList()
    }

    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    return (
        <>
            <Row className="info">
                <Col span={24}>
                    <Flex justify={'space-between'}>
                        <Typography.Title level={3}>账号管理</Typography.Title>
                        <Button
                            type="primary"
                            icon={<PlusOutlined />}
                            onClick={() => setIsModalOpen(true)}
                        >
                            新建账号
                        </Button>
                    </Flex>
                </Col>
            </Row>
            <Row className="container">
                <Col span={24}>
                    <Form form={searchForm} layout="inline" onFinish={handleSearch}>
                        <Form.Item label="用户名" name="username">
                            <Input />
                        </Form.Item>
                        <Form.Item label="手机号" name="phone">
                            <Input />
                        </Form.Item>
                        <Form.Item>
                            <Button type="default" onClick={handleReset}>
                                重置
                            </Button>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                        </Form.Item>
                    </Form>
                </Col>
            </Row>
            <Row className="container">
                <Col span={24}>
                    <Typography.Paragraph style={{ fontSize: 16 }}>
                        账号列表
                    </Typography.Paragraph>
                </Col>
                <Col span={24}>
                    <Table
                        loading={loading}
                        rowKey={(record) => record.id}
                        columns={[
                            {
                                title: '编号',
                                dataIndex: 'id',
                                key: 'id'
                            },
                            {
                                title: '姓名',
                                dataIndex: 'nickname',
                                key: 'nickname'
                            },
                            {
                                title: '商家ID',
                                dataIndex: 'businessId',
                                key: 'businessId',
                                render: (businessId) => businessId || '-'
                            },
                            {
                                title: '用户类型',
                                dataIndex: 'accountType',
                                key: 'accountType',
                                render: (accountType) => accountType === 1 ? '平台' : accountType === 2 ? '商家' : '-'
                            },
                            {
                                title: '手机号',
                                dataIndex: 'accountPhone',
                                key: 'accountPhone'
                            },
                            {
                                title: '电子邮箱',
                                dataIndex: 'email',
                                key: 'email'
                            },
                            {
                                title: '创建时间',
                                dataIndex: 'createTime',
                                key: 'createTime',
                                render: (createTime) => new Date(createTime).toLocaleString()
                            },
                            {
                                title: '状态',
                                key: 'accountStatus',
                                render: (_, record) => (
                                    <Switch
                                        checked={record.accountStatus === 0}
                                        onChange={async (checked) => {
                                            try {
                                                const res = await accountAddAPI({
                                                    ...record,
                                                    accountStatus: checked ? 0 : 1
                                                })
                                                if (res.code === '0') {
                                                    message.success('状态更新成功')
                                                    fetchAccountList()
                                                }
                                            } catch (error) {
                                                message.error('状态更新失败')
                                            }
                                        }}
                                    />
                                )
                            },
                            {
                                title: '操作',
                                key: 'action',
                                render: (_, record) => {
                                    return (
                                        <span className="op">
                      <a
                          onClick={() => {
                              setIsModalOpen(true)
                              form.setFieldsValue(record)
                              setAccountType(record.accountType === 2 ? 1 : 0)
                          }}
                      >
                        编辑
                      </a>
                      <Divider type="vertical" />
                      <a
                          onClick={async () => {
                              Modal.confirm({
                                  title: '确认删除',
                                  content: '确定要删除此账号吗？',
                                  onOk: async () => {
                                      const res = await accountDelAPI({ id: record.id })
                                      if (res.code === '0') {
                                          message.success('删除成功')
                                          fetchAccountList()
                                      }
                                  }
                              })
                          }}
                      >
                        删除
                      </a>
                      <Divider type="vertical" />
                      <a
                          onClick={async () => {
                              Modal.confirm({
                                  title: '确认重置密码',
                                  content: '确定要重置此账号的密码吗？',
                                  onOk: async () => {
                                      const res = await accountResetAPI({ id: record.id })
                                      if (res.code === '0') {
                                          message.success('密码重置成功')
                                      }
                                  }
                              })
                          }}
                      >
                        密码重置
                      </a>
                    </span>
                                    )
                                }
                            }
                        ]}
                        dataSource={accountList}
                        pagination={pagination}
                        onChange={handleTableChange}
                    />
                </Col>
            </Row>
            <Modal
                title={form.getFieldValue('id') ? '编辑账号' : '新建账号'}
                width={800}
                open={isModalOpen}
                onOk={() => {
                    form.submit()
                }}
                onCancel={() => {
                    setIsModalOpen(false)
                    form.resetFields()
                }}
                maskClosable={false}
                destroyOnClose
            >
                <Divider />
                <Form
                    form={form}
                    preserve={false}
                    onFinish={async (values) => {
                        try {
                            const res = await accountAddAPI(values)
                            if (res.code === '0') {
                                message.success(form.getFieldValue('id') ? '编辑账号成功' : '新建账号成功')
                                setIsModalOpen(false)
                                form.resetFields()
                                fetchAccountList()
                            } else {
                                message.error(res.message || '操作失败')
                            }
                        } catch (error) {
                            message.error('操作失败')
                        }
                    }}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                >
                    <Form.Item name="id" hidden>
                        <Input />
                    </Form.Item>
                    <Form.Item label="账号类型" name="accountType" initialValue={0}>
                        <Radio.Group
                            onChange={(e) => {
                                form.setFieldsValue({
                                    accountPassword: '',
                                    businessId: '',
                                })
                                setAccountType(e.target.value)
                            }}
                        >
                            <Radio value={1}>平台</Radio>
                            <Radio value={2}>商家</Radio>
                        </Radio.Group>
                    </Form.Item>

                    {accountType === 1 && (
                        <>
                            <Form.Item
                                label="手机号码"
                                name="accountPhone"
                                rules={[
                                    {
                                        required: true,
                                        message: '电话号码不能为空'
                                    },
                                    {
                                        pattern: /^1[3-9]\d{9}$/,
                                        message: '请输入正确的手机号码'
                                    }
                                ]}
                            >
                                <Input placeholder="请输入11位手机号" />
                            </Form.Item>
                            {!form.getFieldValue('id') && (
                                <Form.Item
                                    label="登录密码"
                                    name="accountPassword"
                                    rules={[
                                        {
                                            required: true,
                                            message: '密码不能为空'
                                        },
                                        {
                                            pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,20}$/,
                                            message: '请输入8~20个字符且包含字母、数字至少一种'
                                        }
                                    ]}
                                >
                                    <Input.Password placeholder="请输入8~20个字符且包含字母、数字至少一种" />
                                </Form.Item>
                            )}
                            <Form.Item
                                label="用户名称"
                                name="nickname"
                                rules={[
                                    {
                                        required: true,
                                        message: '用户名称不能为空'
                                    },
                                    {
                                        pattern: /^.{1,15}$/,
                                        message: '请输入15个字符以内的用户名'
                                    }
                                ]}
                            >
                                <Input placeholder="请输入15个字符以内的用户名" />
                            </Form.Item>
                            <Form.Item
                                label="电子邮箱"
                                name="email"
                                rules={[
                                    {
                                        required: true,
                                        message: '电子邮箱不能为空'
                                    },
                                    {
                                        pattern:
                                            /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                                        message: '请输入正确的电子邮箱'
                                    }
                                ]}
                            >
                                <Input placeholder="请输入电子邮箱" />
                            </Form.Item>
                            <Form.Item label="账号状态" name="accountStatus" initialValue={0}>
                                <Radio.Group>
                                    <Radio value={0}>启用</Radio>
                                    <Radio value={1}>禁用</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </>
                    )}
                    {accountType === 2 && (
                        <>
                            <Form.Item
                                label="归属商家"
                                name="businessId"
                                rules={[
                                    {
                                        required: true,
                                        message: '商家名称不能为空'
                                    }
                                ]}
                            >
                                <Select
                                    placeholder="请选择商家名称"
                                    options={sellerList.map(item => ({
                                        value: item.id,
                                        label: item.businessName
                                    }))}
                                />
                            </Form.Item>
                            <Form.Item
                                label="手机号码"
                                name="accountPhone"
                                rules={[
                                    {
                                        required: true,
                                        message: '电话号码不能为空'
                                    },
                                    {
                                        pattern: /^1[3-9]\d{9}$/,
                                        message: '请输入正确的手机号码'
                                    }
                                ]}
                            >
                                <Input placeholder="请输入11位手机号" />
                            </Form.Item>
                            {!form.getFieldValue('id') && (
                                <Form.Item
                                    label="登录密码"
                                    name="accountPassword"
                                    rules={[
                                        {
                                            required: true,
                                            message: '密码不能为空'
                                        },
                                        {
                                            pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,20}$/,
                                            message: '请输入8~20个字符且包含字母、数字至少一种'
                                        }
                                    ]}
                                >
                                    <Input.Password placeholder="请输入8~20个字符且包含字母、数字至少一种" />
                                </Form.Item>
                            )}
                            <Form.Item
                                label="用户名称"
                                name="nickname"
                                rules={[
                                    {
                                        required: true,
                                        message: '用户名称不能为空'
                                    },
                                    {
                                        pattern: /^.{1,15}$/,
                                        message: '请输入15个字符以内的用户名'
                                    }
                                ]}
                            >
                                <Input placeholder="请输入15个字符以内的用户名" />
                            </Form.Item>
                            <Form.Item
                                label="电子邮箱"
                                name="email"
                                rules={[
                                    {
                                        required: true,
                                        message: '电子邮箱不能为空'
                                    },
                                    {
                                        pattern:
                                            /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                                        message: '请输入正确的电子邮箱'
                                    }
                                ]}
                            >
                                <Input placeholder="请输入电子邮箱" />
                            </Form.Item>
                            <Form.Item label="账号状态" name="accountStatus" initialValue={0}>
                                <Radio.Group>
                                    <Radio value={0}>启用</Radio>
                                    <Radio value={1}>禁用</Radio>
                                </Radio.Group>
                            </Form.Item>
                        </>
                    )}
                </Form>
            </Modal>
        </>
    )
}

export default PrivilegeAccount